//
//  PlaceHomeViewController.m
//  WisdomZhuHai
//
//  Created by Admin on 14-10-20.
//  Copyright (c) 2014年 wyd. All rights reserved.
//

#import "PlaceHomeViewController.h"
#import "ProtocolManager.h"
#import "StoreListViewController.h"
#import "StoreDetailViewController.h"
#import "MovieViewController.h"
#import "HotListModel.h"
#import "HotListTableViewCell.h"
#import "UIWebControl.h"

static const CGSize CATEGORYVIEW_SIZE = {52,82};
static const CGFloat CATEGORYCELL_HEIGHT = 100;
static const CGSize HOTRECOMMENDVIEW_SIZE = {147, 147};
static const CGFloat HOTRECOMMENDCELL_HEIGHT = 158;

@interface PlaceHomeViewController ()<UITableViewDataSource, UITableViewDelegate, UIAlertViewDelegate>{
    NSMutableArray *_model;
    NSMutableArray *_modelList;
    NSMutableArray *_modelCells;
}

@property (nonatomic,assign)int typeListIndex;
@property (nonatomic,assign)int hotListsBannerIndex;
@property (nonatomic,assign)int hotListIndex;

@property (nonatomic,strong) NSArray* typeList;
@property (nonatomic,strong) NSArray* hotList;

@end

@implementation PlaceHomeViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.tableView.backgroundColor = [Common colorWithRGB:0xdbdcdc];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
//    [self setEnableRefresh:YES];
    self.pullTableViewDelegate = self;
    self.tableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, self.tableView.bounds.size.width, 0.f)];
    
    self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, self.tableView.bounds.size.width, 0.f)];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    [self initIndex];
    [self getStoreType];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

- (void) initIndex
{
    self.typeListIndex = 0;
    self.hotListsBannerIndex = 1;
    self.hotListIndex = 2;
}

- (void) changeIndex
{
    self.hotListsBannerIndex = -1;
    self.hotListIndex = 1;
}

#pragma mark - load data

- (void) initData:(NSArray*)array{
    NSLog(@"======>%@",array);
    _modelList = [[NSMutableArray alloc]init];
    _modelCells = [[NSMutableArray alloc]init];
    [array enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        NSLog(@"%@",obj);
        [_modelList addObject:[HotListModel statusWithDictionary:obj]];
        HotListTableViewCell *cell = [[HotListTableViewCell alloc]init];
        [_modelCells addObject:cell];
    }];
}

- (void)onTapCategory:(UITapGestureRecognizer*)gesture
{
    NSLog(@"onTapCategory %d", gesture.view.tag);
    NSString *name = @"";
    for (NSDictionary *dic in self.typeList) {
        int typeId = [[Common valueForKey:P_ID dic:dic] intValue];
        if (typeId == gesture.view.tag) {
            name = [Common valueForKey:P_NAME dic:dic];
        }
    }
    if ([name isEqualToString:@"电影院"]) {
        MovieViewController *listViewCtrl = [[MovieViewController alloc] initWithFrame:[Common shareInstance].contentFrameNoTabBar style:UITableViewStylePlain];
        listViewCtrl.type = gesture.view.tag;
        listViewCtrl.hidesBottomBarWhenPushed = YES;
        [self.navigationCtrl pushViewController:listViewCtrl animated:YES];
    }else{
        StoreListViewController *listViewCtrl = [[StoreListViewController alloc] initWithFrame:[Common shareInstance].contentFrameNoTabBar style:UITableViewStylePlain];
        listViewCtrl.type = gesture.view.tag;
        listViewCtrl.hidesBottomBarWhenPushed = YES;
        [self.navigationCtrl pushViewController:listViewCtrl animated:YES];
    }
}

- (void)onTapHotRecommend:(UITapGestureRecognizer*)gesture
{
    NSLog(@"onTapHotRecommend %d", gesture.view.tag);
    int storeId = gesture.view.tag - 1000;
    StoreDetailViewController *storeDetailViewCtrl = [[StoreDetailViewController alloc] initWithFrame:[Common shareInstance].contentFrameNoTabBar style:UITableViewStylePlain];
    storeDetailViewCtrl.storeId = storeId;
    storeDetailViewCtrl.hidesBottomBarWhenPushed = YES;
    [self.navigationCtrl pushViewController:storeDetailViewCtrl animated:YES];
}

- (void)onShowMore:(UIButton*)sender
{
    NSLog(@"onShowMore");
}

#pragma mark - Protocol request
- (void)getStoreType
{
    [[ProtocolManager shareInstance] getStoreType:self selector:@selector(getStoreTypeCallback:)];
}

#pragma mark - Protocol call back
- (void)getStoreTypeCallback:(NSDictionary*)dic
{
    NSLog(@"getStoreTypeCallback %@", dic);
    if (dic == nil) {
        return;
    }
    id types = [Common valueForKey:P_STORETYPES dic:dic];
    if ([types isKindOfClass:[NSArray class]]) {
        self.typeList = types;
    }
    id hotList = [Common valueForKey:P_HOTLISTS dic:dic];
    if ([hotList isKindOfClass:[NSArray class]]) {
        self.hotList = hotList;
    }
    id hotListsBanner = [Common valueForKey:P_HOTLISTSBANNER dic:dic];
    NSLog(@"======hotList>>%@", hotListsBanner);
    if ([hotListsBanner isKindOfClass:[NSArray class]]) {
        _model = hotListsBanner;
        [self initData:_model];
    }
    if ([_model count] == 0) {
        [self changeIndex];
    }
    [self.tableView reloadData];
}

#pragma mark - Private
- (void)setupCategoryCell:(UITableViewCell*)cell
{
    for (UIView *view in cell.contentView.subviews) {
        if (view.tag > 0) {
            [view removeFromSuperview];
        }
    }
    
    if (self.typeList.count == 0) {
        return;
    }

    CGFloat offsetX = 30;
    CGFloat offsetY = 13;
    CGFloat intervalX = (cell.contentView.frame.size.width - CATEGORYVIEW_SIZE.width*4 - offsetX*2)/3;
    for (int i=0; i<MIN(4, self.typeList.count); i++) {
        NSDictionary* dic = self.typeList[i];
        int typeId = [[Common valueForKey:P_ID dic:dic] intValue];
        NSString* logo = [Common valueForKey:P_LOGO dic:dic];
        NSString* name = [Common valueForKey:P_NAME dic:dic];
        
        NSRange range = [logo rangeOfString:@"/okhaolvxing"];
        if (range.location != NSNotFound) {
            logo = [logo substringFromIndex:range.location + range.length];
        }
        
        UIView *btn = [self createCategoryView:logo title:name];
        btn.tag = typeId;
        
        CGRect frame = btn.frame;
        frame.origin.x = offsetX + i*(CATEGORYVIEW_SIZE.width+intervalX);
        frame.origin.y = offsetY;
        btn.frame = frame;
        
        [cell.contentView addSubview:btn];
    }
}

- (UIView*)createCategoryView:(NSString*)icon title:(NSString*)title
{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, CATEGORYVIEW_SIZE.width, CATEGORYVIEW_SIZE.height)];
    
    UIImageView* imgView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, CATEGORYVIEW_SIZE.width, CATEGORYVIEW_SIZE.width)];
    [imgView setImageWithURL:[Common getFullDownloadPathByRelativePath:icon] placeholderImage:[Common getPlaceholderImage:ePIT_StoreType]];
    [view addSubview:imgView];
    
    UILabel *lbTitle = [[UILabel alloc] initWithFrame:CGRectMake(0, CATEGORYVIEW_SIZE.width, CATEGORYVIEW_SIZE.width, CATEGORYVIEW_SIZE.height - CATEGORYVIEW_SIZE.width)];
    lbTitle.font = [UIFont systemFontOfSize:13];
    lbTitle.backgroundColor = [UIColor clearColor];
    lbTitle.textColor = [UIColor blackColor];
    lbTitle.text = title;
    lbTitle.textAlignment = NSTextAlignmentCenter;
    [view addSubview:lbTitle];
    
    UITapGestureRecognizer *gesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(onTapCategory:)];
    gesture.cancelsTouchesInView = NO;
    [view addGestureRecognizer:gesture];
    
    return view;
}

- (void)setupHotRecommendCell:(UITableViewCell*)cell indexPath:(NSIndexPath*)indexPath
{
    cell.contentView.backgroundColor = self.tableView.backgroundColor;
    for (UIView *view in cell.contentView.subviews) {
        if (view.tag >= 1000) {
            [view removeFromSuperview];
        }
    }
    
    CGFloat intervalX = (cell.contentView.frame.size.width - HOTRECOMMENDVIEW_SIZE.width*2)/3;
    for (int i=0; i<2; i++) {
        int index = indexPath.row*2 + i;
        if (index >= self.hotList.count) {
            break;
        }
        NSDictionary* dic = self.hotList[index];
        NSString *logo = [Common valueForKey:P_PIC_URL dic:dic];
        NSString *name = [Common valueForKey:P_NAME dic:dic];
        int Id = [[Common valueForKey:P_ID dic:dic] intValue];
        UIView* view = [self createHotRecommendView:logo title:name description:nil];
        view.tag = 1000 + Id;
        
        CGRect frame = view.frame;
        frame.origin.x = intervalX + i*(HOTRECOMMENDVIEW_SIZE.width+intervalX);
        frame.origin.y = HOTRECOMMENDCELL_HEIGHT - HOTRECOMMENDVIEW_SIZE.height;
        view.frame = frame;
        
        [cell.contentView addSubview:view];
    }
}

- (UIView*)createHotRecommendView:(NSString*)icon title:(NSString*)title description:(NSString*)description
{
    UIImageView* imgView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, HOTRECOMMENDVIEW_SIZE.width, HOTRECOMMENDVIEW_SIZE.height)];
    imgView.userInteractionEnabled = YES;
    [imgView setImageWithURL:[Common getFullDownloadPathByRelativePath:icon] placeholderImage:[Common getPlaceholderImage:ePIT_StoreLogo]];
    
    UILabel *lbTitle = [[UILabel alloc] initWithFrame:CGRectMake(8.5, 114, HOTRECOMMENDVIEW_SIZE.width-17, 20)];
    lbTitle.font = [UIFont boldSystemFontOfSize:16];
    lbTitle.backgroundColor = [UIColor clearColor];
    lbTitle.textColor = [UIColor whiteColor];
    lbTitle.text = title;
    [imgView addSubview:lbTitle];
    
//    UILabel *lbDescription = [[UILabel alloc] initWithFrame:CGRectMake(8.5, 130, HOTRECOMMENDVIEW_SIZE.width-17, HOTRECOMMENDVIEW_SIZE.height - 132)];
//    lbDescription.font = [UIFont systemFontOfSize:12];
//    lbDescription.backgroundColor = [UIColor clearColor];
//    lbDescription.textColor = [UIColor whiteColor];
//    lbDescription.text = description;
//    [imgView addSubview:lbDescription];
    
    UITapGestureRecognizer *gesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(onTapHotRecommend:)];
    gesture.cancelsTouchesInView = NO;
    [imgView addGestureRecognizer:gesture];
    
    return imgView;
}

#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    if (_hotListsBannerIndex == -1) {
        return 2;
    }
    return 3;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == _typeListIndex) {
        return 1;
    }else if(section == _hotListsBannerIndex){
        return _model.count>4?4:_model.count;
        //return 2;
    }
    else {
        return 2;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.section == _typeListIndex) {
        return CATEGORYCELL_HEIGHT;
    }else if(indexPath.section == _hotListsBannerIndex){
        HotListTableViewCell *cell = _modelCells[indexPath.row];
        cell.model = _model[indexPath.row];
        return cell.height;
    }
    else if (indexPath.section == _hotListIndex) {
        return HOTRECOMMENDCELL_HEIGHT;
    }
    else {
        return 0;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section > 0) {
        return 26;
    }
    else {
        return 0;
    }
}

- (UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView* view = [[UIView alloc] init];
    view.backgroundColor = [Common colorWithRGB:0xf3f3f3];
    if (section == 1) {
        UILabel *lb = [[UILabel alloc] initWithFrame:CGRectMake(17, 0.5, 80, 25.5)];
        lb.backgroundColor = [UIColor clearColor];
        lb.text = @"热门推荐";
        lb.font = [UIFont systemFontOfSize:15];
        lb.textColor = [Common colorWithRGB:0x393a3a];
        [view addSubview:lb];
        
//        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
//        btn.frame = CGRectMake(self.view.bounds.size.width - 25, 3, 20, 20);
//        [btn setImage:[UIImage imageNamed:@"where/more1.png"] forState:UIControlStateNormal];
//        [btn setImage:[UIImage imageNamed:@"where/more2.png"] forState:UIControlStateHighlighted];
//        btn.imageView.contentMode = UIViewContentModeCenter;
//        [btn addTarget:self action:@selector(onShowMore:) forControlEvents:UIControlEventTouchUpInside];
//        [view addSubview:btn];
    }
    
    return view;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = nil;
        if (indexPath.section == _typeListIndex)
        {
            cell = [tableView dequeueReusableCellWithIdentifier:@"CategoryCell"];
            // Configure the cell...
            if(cell == nil)
            {
                cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"CategoryCell"];
                cell.contentView.backgroundColor = [Common colorWithRGB:0xf3f3f3];
                UIImageView *imgView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"where/cut-offrule.png"]];
                imgView.center = CGPointMake(cell.bounds.size.width/2, CATEGORYCELL_HEIGHT-0.5);
                [cell.contentView addSubview:imgView];
            }
            [self setupCategoryCell:cell];
        }
        else if (indexPath.section == _hotListsBannerIndex)
        {
            HotListTableViewCell *hCell;
            hCell = [tableView dequeueReusableCellWithIdentifier:@"HotListCell"];
            if(!hCell){
                hCell = [[HotListTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"HotListCell"];
            }
            HotListModel *model = _model[indexPath.row];
            hCell.model = model;
            cell = hCell;
        }
        else if (indexPath.section == _hotListIndex)
        {
            cell = [tableView dequeueReusableCellWithIdentifier:@"HotRecommendCell"];
            // Configure the cell...
            if(cell == nil)
            {
                cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"HotRecommendCell"];
            }
            [self setupHotRecommendCell:cell indexPath:indexPath];
        }
        else
        {
            cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];
            // Configure the cell...
            if(cell == nil)
            {
                cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"Cell"];
            }
        }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}


#pragma mark - Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.section == _hotListsBannerIndex)
    {
        NSDictionary *dic = _model[indexPath.row];
        NSString *path = [Common valueForKey:P_LINK_URL dic:dic];
        int storeId = [[Common valueForKey:P_ID dic:dic] integerValue];
        if (path != nil) {
            NSURL *url = [NSURL URLWithString:path];
            WebIOS *webCtrl = [[WebIOS alloc] initWithFrame:self.view.bounds url:url];
            [self.navigationController pushViewController:webCtrl animated:YES];
        }
        if (storeId != 0) {
            StoreDetailViewController *storeDetailViewCtrl = [[StoreDetailViewController alloc] initWithFrame:[Common shareInstance].contentFrameNoTabBar style:UITableViewStylePlain];
            storeDetailViewCtrl.storeId = storeId;
            storeDetailViewCtrl.hidesBottomBarWhenPushed = YES;
            [self.navigationCtrl pushViewController:storeDetailViewCtrl animated:YES];
        }
    }
}

#pragma mark - PullTableViewDelegate
- (void)pullTableViewDidTriggerRefresh:(PullTableView*)pullTableView
{
    NSLog(@"refresh...");
}

-(void)pullTableViewDidTriggerLoadMore:(PullTableView *)pullTableView
{
    NSLog(@"loadMore...");
}

- (void)resetPullTableViewState
{
    [self setPullTableIsRefreshing:NO];
    [self setPullTableIsLoadMore:NO];
}


@end
